#ifndef GITEE_M_MUTEX_H
#define GITEE_M_MUTEX_H

#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#include <unistd.h>

class MMutex
{
public:
    MMutex() { pthread_mutex_init(&mtx_,NULL); }
    ~MMutex() { pthread_mutex_destroy( &mtx_ ); }

    void lock() { pthread_mutex_lock( &mtx_ ); }
    int trylock() { return pthread_mutex_trylock( &mtx_ ); }
    void unlock() { pthread_mutex_unlock( &mtx_ ); }

    pthread_mutex_t *mtx() { return &mtx_; }
private:
    pthread_mutex_t mtx_;
};

class MSem {
public:
    MSem() { sem_init(&sem_, 0, 0); }
    ~MSem() { sem_destroy(&sem_); }

    int wait() { return sem_wait(&sem_); }
    int timedwait(size_t ms) {
        do {
            if( sem_trywait(&sem_) == 0 )
                return 0;
            usleep(1000);
        } while(ms--);

        return sem_trywait(&sem_);
    }

    int post() { return sem_post(&sem_); }
    int getvalue(int &val) { return sem_getvalue(&sem_, &val); }

private:
    sem_t sem_;
};

#endif
